﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using GroupChat2013.Entity;
using GroupChat2013.Service;
using GroupChat2013.Common;
using System.IO;
using CCWin;
using GroupChat2013.Logic;

namespace GroupChat2013.Main.Controls
{
    public partial class UploadItem : UserControl
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        private HttpProc.WebClient m_WebClient;

        /// <summary>
        /// 服务
        /// </summary>
        private ServiceUrlProxy m_ServiceUrlProxy = ServiceUrlProxy.GetInstance();

        /// <summary>
        /// 上传文件路径
        /// </summary>
        public string FilePath { get; set; }

        /// <summary>
        /// 容器
        /// </summary>
        private UploadPanel m_Ower;

        private ObjTalker m_ObjTalker;

        /// <summary>
        /// 上传线程
        /// </summary>
        private Thread m_Thread;

        private readonly double MB = 1024 * 1024;
        private readonly int KB = 1024;

        /// <summary>
        /// 上传完成事件
        /// </summary>
        public event Action<ShareResultInfo> UploadCompeled;

        public UploadItem()
        { 
        
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="file"></param>
        public UploadItem(UploadPanel panel, string file, ObjTalker talker)
        {
            InitializeComponent();

            Init();
            this.BackColor = Color.Transparent;

            m_Ower = panel;
            FilePath = file;
            m_ObjTalker = talker;
            progressBar1.Value = 0;

            FileInfo fileInfo = new FileInfo(file);
            if (fileInfo != null)
            {
                lbFileName.Text = fileInfo.Name.Length > 19 ? fileInfo.Name.Substring(0, 19) + "..." : fileInfo.Name;
            }
        }

        private void Init()
        {
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.SetStyle(ControlStyles.StandardDoubleClick, false);
            this.SetStyle(ControlStyles.Selectable, true);
            this.UpdateStyles();
        }

        /// <summary>
        /// 开始上传 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BeginUpload()
        {
            m_Thread = new Thread(new ThreadStart(() =>
            {
                try
                {
                    m_WebClient = new HttpProc.WebClient();
                    m_WebClient.Encoding = Encoding.UTF8;
                    m_WebClient.UploadProgressChanged += new HttpProc.WebClientUploadEvent(m_WebClient_UploadProgressChanged);

                    string cid = EngineContext.Current.CurrUserInfo.CID;

                    string value = string.Empty;
                    if (m_ObjTalker.TypeChat == ChatType.Group)
                        value = m_WebClient.UploadFileWithCookie(ServiceUrlProxy.GetInstance().UploadGroupFileURL(m_ObjTalker.GroupInfo.groupId),
                            "", string.Format(@"file={0}", FilePath), "cid=" + cid);
                    else
                        value = m_WebClient.UploadFileWithCookie(ServiceUrlProxy.GetInstance().UploadUserFileURL(m_ObjTalker.FriendInfo.userInfoId),
                            "", string.Format(@"file={0}", FilePath), "cid=" + cid);

                    value = value.Substring(value.IndexOf('{'));
                    ShareResultInfo resultInfo = JsonConvert.Parse<ShareResultInfo>(value);

                    IAsyncResult result = m_Ower.BeginInvoke(new Action(() =>
                    {
                        m_Ower.Controls.Remove(this);
                        if (UploadCompeled != null)
                        {
                            resultInfo = resultInfo ?? new ShareResultInfo();
                            string desStr = "{0} 发送{1}";
                            desStr = string.Format(desStr, FilePath, resultInfo.IsSucess ? "成功" : "失败");
                            resultInfo.CompeledStr = desStr;

                            UploadCompeled(resultInfo);
                        }
                    }));

                    this.EndInvoke(result);
                }
                catch
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        MessageBoxEx.Show("文件发送失败，可能已主动取消或网络出现问题", "提示",
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        m_Ower.Controls.Remove(this);
                    }));
                }
            }));

            m_Thread.Start();
        }

        /// <summary>
        /// 更新上传进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_WebClient_UploadProgressChanged(object sender, HttpProc.UploadEventArgs e)
        {
            IAsyncResult result = this.BeginInvoke(new Action(() =>
            {
                progressBar1.Value = Convert.ToInt32(e.sendProgress * 100);
                lbSpeed.Text = e.sendSpeed > MB ? (e.sendSpeed / MB).ToString("0.00") + "mb/s" : (e.sendSpeed / KB).ToString("0.00") + "kb/s";
            }));

            this.EndInvoke(result);
        }

        /// <summary>
        /// 取消上传
        /// </summary>
        public void CancelUpload()
        {
            try
            {
                if (m_WebClient != null)
                    m_WebClient.Cancel();

                m_Ower.Controls.Remove(this);

                if (m_Thread != null)
                    m_Thread.Abort();

                if (UploadCompeled != null)
                {
                    ShareResultInfo resultInfo = new ShareResultInfo();
                    string desStr = string.Format("{0} 已经取消发送！", FilePath);
                    resultInfo.CompeledStr = desStr;
                    UploadCompeled(resultInfo);
                }
            }
            catch { }
        }
         
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            CancelUpload();
        }

        /// <summary>
        /// 正在上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnsend_Click(object sender, EventArgs e)
        {
            btnsend.Enabled = false;
            btnsend.Text = "正在发送";
            BeginUpload();
        }
    }
}
